<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body" v-show="cartList.length">
        <!-- 购物车列表渲染 -->
        <ul class="cart-list" v-for="item in cartList" :key="item.id">
          <li class="cart-list-con1">
            <!-- 多选框 -->
            <input type="checkbox" name="chk_list" @click="updateIsChecked(item)" :checked="Boolean(item.isChecked)" />
          </li>
          <li class="cart-list-con2">
            <img :src="item.imgUrl" />
            <div class="item-msg">{{ item.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ item.cartPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <el-input-number v-model="item.skuNum" :min="1" :max="200" size="small" @change="handleChange($event, item)" />
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ item.skuNum * item.cartPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="delCart(item)">删除</a>
            <br />
          </li>
        </ul>
      </div>
    </div>
    <!-- 底部结算 -->
    <div class="cart-tool" v-show="cartList.length">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" :checked="isAllChecked" @change="updateAllChecked" />
        <span>全选</span>
      </div>
      <div class="option">
        <button @click="delAllCart" :disabled="isDisabled">删除选中的商品</button>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ checkedCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" target="_blank" @click="goToPay">结算</a>
        </div>
      </div>
    </div>
    <!-- 暂无数据 -->
    <div v-show="!cartList.length" class="empty">
      <h1>购物车空空如也！</h1>
      <img src="http://49.232.112.44/images/empty.gif" alt="" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { reqCheckCart, reqAddCart, reqDeleteCart, reqBatchCheckCart, reqBatchDeleteCart } from '@/api/cart'
import { reqCartList } from '@/api/cart'
import type { cartInfoList, ISkuIdList } from '@/types/cart'
import _ from 'lodash'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'

// 购物车列表数据
const cartList = ref<cartInfoList[]>([])

// 获取购物车列表数据
const getCartList = async () => {
 const {data} = await reqCartList()
 data.forEach((item) => {
  cartList.value = item.cartInfoList
 })
}

// 更新单个商品的选中状态
const updateIsChecked = async (item: cartInfoList) => {
  const { skuId, isChecked } = item
  // 判断勾选的状态
  const newIsChecked = isChecked === 0 ? 1 : 0
  // 发送请求
  const res = await reqCheckCart(skuId, newIsChecked)
  if (res.code === 200) {
    item.isChecked = newIsChecked
  }
}

// 点击全选多选框
const updateAllChecked = async (event: any) => {
  let { checked } = event.target
  checked = checked ? 1 : 0
  // 定义一个新数组
  const skuIdList: any[] = []
  cartList.value.forEach((item: cartInfoList) => skuIdList.push(item.skuId))
  const res = await reqBatchCheckCart(checked, skuIdList as any)
  if (res.code === 200) {
    cartList.value.forEach((item: cartInfoList) => (item.isChecked = checked))
  }
}

// 购物车数量的加减
const handleChange = _.debounce(async function (event: any, item: cartInfoList) {
  // 获取更新后的数据
  const newNum = event
  // 解构数据
  const { skuId, skuNum } = item
  // 获取差值
  const disNum = newNum - skuNum
  // 发送请求
  await reqAddCart(skuId, disNum)
  // 更新数据
  item.skuNum = newNum
}, 800)

// 删除单个商品
const delCart = async (item: cartInfoList) => {
  // 展示弹框
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let id = item.skuId
    const res = await reqDeleteCart(id)
    if (res.code === 200) {
      // 查找删除的下标
      const index = cartList.value.findIndex((item) => item.skuId === id)
      // 删除
      cartList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }) .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除选中商品
const delAllCart = () => {
  ElMessageBox.confirm('确定要删除选中商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 新建删除的商品列表
      let newCartList = [] as ISkuIdList
      // 遍历购物车列表
      cartList.value.forEach((item: cartInfoList) => {
        // 判断是否选中
        if (item.isChecked) {
          // 选中添加到新列表
          newCartList.push(item.skuId)
        }
      })
      // 发送请求
      const res = await reqBatchDeleteCart(newCartList)

      if (res.code === 200) {
        cartList.value = cartList.value.filter((item) => !item.isChecked)
      }
      ElMessage({
        type: 'success',
        message: '删除成功！'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消了删除'
      })
    })
}

// 计算属性，全选与取消全选
const isAllChecked = computed(() => {
  return cartList.value.every((item: cartInfoList) => item.isChecked === 1)
})

// 计算属性，删除多个商品的禁止选中
const isDisabled = computed(() => {
  return !cartList.value.some((item) => item.isChecked)
})

// 计算属性，计算选中的商品个数
const checkedCount = computed(() => {
  return cartList.value.reduce((prev, item) => {
    if (item.isChecked) {
      prev += item.skuNum
    }
    return prev
  }, 0)
})

// 计算属性， 计算商品总价格
const totalPrice = computed(() => {
  return cartList.value.reduce((prev, item) => {
    if (item.isChecked) {
      prev += item.cartPrice * item.skuNum
    }
    return prev
  }, 0)
})

// 跳转到结算页面
const goToPay = () => {
  router.push('/trade')
}

onMounted(() => {
  getCartList()
})
</script>

<script lang="ts">
export default {
  name: 'CartView'
}
</script>

<style lang="scss" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  .empty {
    margin-top: 30px;
    text-align: center;
    img {
      width: 300px;
    }
    h1 {
      color: rgb(158, 155, 155);
    }
  }
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      button {
        display: block;
        position: relative;
        width: 96px;
        height: 30px;
        color: #fff;
        text-align: center;
        font-family: 'Microsoft YaHei';
        background: #e1251b;
        overflow: hidden;
        text-decoration: none;
        cursor: pointer;
        border: 0;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
</style>
